package com.gxnzd.communityelderly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxnzd.communityelderly.commom.MapUtil;
import com.gxnzd.communityelderly.commom.R;
import com.gxnzd.communityelderly.dao.DoctorScheduling;
import com.gxnzd.communityelderly.entity.Employee;
import com.gxnzd.communityelderly.entity.Reservation;
import com.gxnzd.communityelderly.entity.Scheduling;
import com.gxnzd.communityelderly.mapper.ReservationMapper;
import com.gxnzd.communityelderly.service.EmployeeService;
import com.gxnzd.communityelderly.service.SchedulingService;
import com.gxnzd.communityelderly.mapper.SchedulingMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author 23234
* @description 针对表【scheduling】的数据库操作Service实现
* @createDate 2024-10-31 15:23:29
*/
@Service
public class SchedulingServiceImpl extends ServiceImpl<SchedulingMapper, Scheduling>
    implements SchedulingService{

    @Resource
    private SchedulingMapper schedulingMapper;

    @Resource
    private ReservationMapper reservationMapper;

    @Resource
    private EmployeeService employeeService;

    /**
     * 传入时间戳获取星期几
     * @param date
     * @return
     */
    public String getWeek(Date date){
        String[] weeks = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }
        return weeks[week_index];
    }

    public boolean isEdit(String week,Scheduling scheduling,Reservation reservation) throws Exception{
        Map<String, Object> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        switch (week){
            case "monday":
                map = objectMapper.readValue(scheduling.getMonday(), Map.class);
                break;
            case "tuesday":
                map = objectMapper.readValue(scheduling.getTuesday(), Map.class);
                break;
            case "wednesday":
                map = objectMapper.readValue(scheduling.getWednesday(), Map.class);
                break;
            case "thursday":
                map = objectMapper.readValue(scheduling.getThursday(), Map.class);
                break;
            case "friday":
                map = objectMapper.readValue(scheduling.getFriday(), Map.class);
                break;
            case "saturday":
                map = objectMapper.readValue(scheduling.getSaturday(), Map.class);
                break;
            case "sunday":
                map = objectMapper.readValue(scheduling.getSunday(), Map.class);
                break;
        }

        Object morning = map.get("morning");
        Object afternoon = map.get("afternoon");
       if(reservation.getAppointmentTime().equals("morning") && (Integer)morning == 1){
           return true;
         }else if(reservation.getAppointmentTime().equals("afternoon") && (Integer)afternoon == 1){
            return true;
        }else{
           return false;
        }


    }

    /**
     * 添加/修改排班
     * @param scheduling
     * @return
     */
    @Override
    public R appendScheduling(Scheduling scheduling) {
        Employee employee = employeeService.getById(scheduling.getDoctorId());
        if (employee == null){
            return R.error("没有此人员");
        }
        if(employee.getType() != 3){
            return R.error("此用户并非是医生");
        }
        scheduling.setCommunityId(employee.getCommunityId());

        //如果已经有了这条排班记录就进行修改
        if (scheduling.getSchedulingId() != null){
            //在修改排班的时候查询预约表中预约人中有没有预约到的班次
            //预约用户预约的班次不能下班
            LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Reservation::getDoctorId,scheduling.getDoctorId())
                    .eq(Reservation::getStatus,"1");
            List<Reservation> list = reservationMapper.selectList(wrapper);

            for (Reservation item:list) {
                Date date = item.getAppointmentDate();
                String week = getWeek(date);
              try {
                  boolean edit = isEdit(week, scheduling, item);
                  //edit为true 表示能修改此条排班记录
                  if (!edit){
                      return R.error("修改的班次中有用户预约");
                  }
              }catch (Exception e){
                  e.printStackTrace();
                  return R.error("发生错误！");
              }


            }
            //能修改
            schedulingMapper.updateById(scheduling);
        }else{
            schedulingMapper.insert(scheduling);
        }
        return R.success("操作成功");
    }

    /**
     * 将某个医生的排班记录回归到无
     * @param id
     * @return
     */
    @Override
    public R clearScheduling(Long id) {
        String monday = new String("{\"morning\":0,\"afternoon\":0}");
        String tuesday = new String("{\"morning\":0,\"afternoon\":0}");
        String wednesday = new String("{\"morning\":0,\"afternoon\":0}");
        String thursday = new String("{\"morning\":0,\"afternoon\":0}");
        String friday = new String("{\"morning\":0,\"afternoon\":0}");
        String saturday = new String("{\"morning\":0,\"afternoon\":0}");
        String sunday = new String("{\"morning\":0,\"afternoon\":0}");
        //        //获取这个id的排班记录
        Scheduling scheduling = schedulingMapper.selectById(id);
        scheduling.setMonday(monday);
        scheduling.setTuesday(tuesday);
        scheduling.setWednesday(wednesday);
        scheduling.setThursday(thursday);
        scheduling.setFriday(friday);
        scheduling.setSaturday(saturday);
        scheduling.setSunday(sunday);

        //预约用户预约的班次不能下班
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Reservation::getDoctorId,scheduling.getDoctorId())
                .eq(Reservation::getStatus,"1");
        List<Reservation> list = reservationMapper.selectList(wrapper);
        for (Reservation item:list) {
            Date date = item.getAppointmentDate();
            String week = getWeek(date);
            try {
                boolean edit = isEdit(week, scheduling, item);
                //edit为true 表示能修改此条排班记录
                if (!edit) {
                    return R.error("修改的班次中有用户预约");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("发生错误！");
            }
        }


        schedulingMapper.updateById(scheduling);
        return R.success("重置成功");
    }

    /**
     * 查询社区id的排班列表
     * @param communityId
     * @return
     */
    @Override
    public R getCommunityList(Long communityId) {
        LambdaQueryWrapper<Scheduling> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Scheduling::getCommunityId,communityId);
        ArrayList<DoctorScheduling> doctorSchedulingList = new ArrayList<>();
        //获取排班信息
        List<Scheduling> list = schedulingMapper.selectList(wrapper);
        //获取医生信息
        for (Scheduling scheduling:list) {
            Employee employee = employeeService.getById(scheduling.getDoctorId());
            DoctorScheduling doctorScheduling = new DoctorScheduling();
            doctorScheduling.setEmployee(employee);
            doctorScheduling.setScheduling(scheduling);
            doctorSchedulingList.add(doctorScheduling);
        }
        return R.success(doctorSchedulingList);
    }

    /**
     * 获取某个医生的排班信息
     * @param empId
     * @return
     */
    @Override
    public R getDoctorOne(Integer empId) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getEmpId,empId);
        Employee employee = employeeService.getOne(wrapper);
        if (employee == null){
            return R.error("没有此用户");
        }
        if (employee.getType() != 3){
            return R.error("此用户不是医生");
        }
        LambdaQueryWrapper<Scheduling> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Scheduling::getDoctorId,employee.getEmpId());
        Scheduling selectOne = schedulingMapper.selectOne(queryWrapper);
        return R.success(selectOne);
    }
}




